package com.weijing.pretty_app.util

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.weijing.pretty_app.R
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin

class HalfCircleSeekBar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {

    private var progress = 0  // 0 - maxValue
    private var maxValue = 100
    private var minValue = 0

    private var strokeWidth = dpToPx(10f)
    private var thumbRadius = dpToPx(8f) // 半径，所以手柄是16dp

    private var radius = 0f
    private var centerX = 0f
    private var centerY = 0f
    private lateinit var rectF: RectF

    private val paintBackground = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        style = Paint.Style.STROKE
        strokeWidth = this@HalfCircleSeekBar.strokeWidth
    }

    private val paintProgress = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = this@HalfCircleSeekBar.strokeWidth
        strokeCap = Paint.Cap.ROUND
    }

    private val paintThumb = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    init {
        context.theme.obtainStyledAttributes(attrs, R.styleable.HalfCircleSeekBar, 0, 0).apply {
            try {
                progress =
                    getInteger(R.styleable.HalfCircleSeekBar_defaultProgress, 0).coerceIn(0, 100)
                maxValue = getInteger(R.styleable.HalfCircleSeekBar_maxValue, 100).coerceAtLeast(1)
                minValue = getInteger(R.styleable.HalfCircleSeekBar_minValue, 0).coerceAtLeast(0)

                if (!hasValue(R.styleable.HalfCircleSeekBar_progressColor)) {
                    throw IllegalArgumentException("progressColor must be defined in XML")
                }
                if (!hasValue(R.styleable.HalfCircleSeekBar_thumbColor)) {
                    throw IllegalArgumentException("thumbColor must be defined in XML")
                }

                paintProgress.color = getColor(R.styleable.HalfCircleSeekBar_progressColor, 0)
                paintThumb.color = getColor(R.styleable.HalfCircleSeekBar_thumbColor, 0)

                // 读取自定义 strokeWidth 和 thumbRadius（使用 px 单位）
//                strokeWidth = getDimension(R.styleable.HalfCircleSeekBar_strokeWidth, strokeWidth)
//                thumbRadius = getDimension(R.styleable.HalfCircleSeekBar_thumbRadius, thumbRadius)
                strokeWidth = getDimension(R.styleable.HalfCircleSeekBar_strokeWidth, 0f)
                thumbRadius = getDimension(R.styleable.HalfCircleSeekBar_thumbRadius, 0f)
            } finally {
                recycle()
            }
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        val padding = max(strokeWidth, thumbRadius)
        radius = (w - 2 * padding) / 2f
        centerX = w / 2f
        centerY = h.toFloat() - thumbRadius  // 关键！半圆底边贴底部，顶部自然呈弧

        rectF = RectF(
            centerX - radius,
            centerY - radius,
            centerX + radius,
            centerY + radius
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val adjustedProgress = progress - minValue
        val adjustedMax = maxValue - minValue

        val sweepAngle = 180f * adjustedProgress / adjustedMax.toFloat()
        // 背景弧
        canvas.drawArc(rectF, 180f, 180f, false, paintBackground)

        // 进度弧
        canvas.drawArc(rectF, 180f, sweepAngle, false, paintProgress)

        // 画手柄
        val angle = 180f * adjustedProgress / adjustedMax
        val angleRad = Math.toRadians(angle.toDouble())
        val thumbX = (centerX - radius * cos(angleRad)).toFloat()
        val thumbY = (centerY - radius * sin(angleRad)).toFloat()

        canvas.drawCircle(thumbX, thumbY, thumbRadius, paintThumb)
    }

    //触摸圆球进行滑动禁止了目前
    /*override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN) {
            val x = event.x - centerX
            val y = event.y - centerY

            val angle = (Math.toDegrees(atan2(y.toDouble(), x.toDouble())) + 360) % 360

            if (angle in 180.0..360.0) {
                progress = (((angle - 180) / 180.0) * maxValue).toInt().coerceIn(0, maxValue)

                progressChangeListener?.onProgressChanged(progress) // 实时回调
                invalidate()
            }
            return true
        }
        return super.onTouchEvent(event)
    }*/

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = ((width / 2f) + thumbRadius + strokeWidth).toInt() // 自动增加顶部空间
        setMeasuredDimension(width, height)
    }

    interface OnProgressChangeListener {
        fun onProgressChanged(progress: Int)
    }

    private var progressChangeListener: OnProgressChangeListener? = null

    fun setOnProgressChangeListener(listener: OnProgressChangeListener) {
        this.progressChangeListener = listener
    }

    fun setProgress(value: Int) {
        progress = value.coerceIn(minValue, maxValue)
        invalidate()
    }

    fun setMax(value: Int) {
        maxValue = value.coerceAtLeast(minValue + 1)
        progress =  progress.coerceIn(minValue, maxValue)
        invalidate()
    }

    fun setMin(value:Int){
        minValue = value.coerceAtLeast(0)
        progress = progress.coerceAtLeast(minValue)
        invalidate()
    }
    fun getMin(): Int = minValue

    fun getProgress(): Int = progress

    private fun dpToPx(dp: Float): Float =
        dp * context.resources.displayMetrics.density
}